#!/bin/bash


yum install wget gzip unzip -y > /dev/null 2>&1
mkdir /etc/wireguard/ > /dev/null 2>&1

cd /etc/wireguard/

CURRENT_DIR=$(
    cd "$(dirname "$0")"
    pwd
)
echo > ${CURRENT_DIR}/install.log

function log() {
    message="[WireGuard Log]: $1 "
    echo -e "${message}" 2>&1 | tee -a ${CURRENT_DIR}/install.log
}


curl -O https://gitee.com/zerohacker/other-downloads/raw/master/linux/Centos_x86_64/7/wireguard-vpn/kmod-wireguard-1.0.20220627-1.el7_9.elrepo.x86_64.rpm
curl -O https://gitee.com/zerohacker/other-downloads/raw/master/linux/Centos_x86_64/7/wireguard-vpn/qrencode-3.4.1-3.el7.x86_64.rpm
curl -O https://gitee.com/zerohacker/other-downloads/raw/master/linux/Centos_x86_64/7/wireguard-vpn/wireguard-tools-1.0.20210914-1.el7.x86_64.rpm
wget https://gitee.com/zerohacker/other-downloads/releases/download/v0.1.0/wireguard-ui-v0.5.1-linux-amd64.tar.gz

tar xf wireguard-ui-v0.5.1-linux-amd64.tar.gz -C /usr/sbin/

yum install *.rpm -y


cat > /etc/systemd/system/wireguard-ui.service <<EOF
[Unit]
Description=wireguard-ui
After=network.target
Wants=network.target
[Service]
User=root
Restart=always
ExecStart=/usr/sbin/wireguard-ui -bind-address "0.0.0.0:50010"
RestartPreventExitStatus=1
[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/wgui.service << EOF
[Unit]
Description=Restart WireGuard
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart wg-quick@wg0.service

[Install]
RequiredBy=wgui.path
EOF

cat > /etc/systemd/system/wgui.path << EOF
[Unit]
Description=Watch /etc/wireguard/wg0.conf for changes

[Path]
PathModified=/etc/wireguard/wg0.conf

[Install]
WantedBy=multi-user.target
EOF

modprobe wireguard

systemctl daemon-reload
systemctl enable wgui.{path,service} wireguard-ui
systemctl restart wgui.{path,service} wireguard-ui
systemctl status wgui.{path,service} wireguard-ui

rm -rf kmod-wireguard-1.0.20220627-1.el7_9.elrepo.x86_64.rpm qrencode-3.4.1-3.el7.x86_64.rpm wireguard-tools-1.0.20210914-1.el7.x86_64.rpm wireguard-ui-v0.5.1-linux-amd64.tar.gz

cat << EOF
██╗       ██╗██╗██████╗ ███████╗ ██████╗ ██╗   ██╗ █████╗ ██████╗ ██████╗ 
██║  ██╗  ██║██║██╔══██╗██╔════╝██╔════╝ ██║   ██║██╔══██╗██╔══██╗██╔══██╗
╚██╗████╗██╔╝██║██████╔╝█████╗  ██║  ██╗ ██║   ██║███████║██████╔╝██║  ██║
 ████╔═████║ ██║██╔══██╗██╔══╝  ██║  ╚██╗██║   ██║██╔══██║██╔══██╗██║  ██║
 ╚██╔╝ ╚██╔╝ ██║██║  ██║███████╗╚██████╔╝╚██████╔╝██║  ██║██║  ██║██████╔╝
  ╚═╝   ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ 
EOF

LOCAL_IP=`hostname --ip-address`

function Show_Result(){
    log ""
    log "=================感谢您的耐心等待，安装已经完成=================="
    log ""
    log "请用浏览器访问WireGuard管理面板:"
    log "面板地址: http://$LOCAL_IP:50010"
    log "用户名称: admin"
    log "用户密码: admin"
    log ""
    log "如果使用的是云服务器，请至安全组开放 50010/TCP,51820/UDP 端口"
    log ""
    log "================================================================"
}

Show_Result
